/**
 * 收藏相关API接口
 * 基于后端API文档：我的模块API.md
 */

import type {
  BatchDeleteFavoritesReqVO,
  BatchDeleteFavoritesResponse,
  DeleteFavoriteResponse,
  FavoriteItem,
  FavoriteItemType,
  GetFavoriteAudiosResponse,
  GetFavoriteBookSetsResponse,
  GetFavoriteBooksResponse,
  PageParams,
} from '@/types/favorites'
import { http, httpDeleteWithBody } from '@/utils/request'

/**
 * 获取收藏绘本列表
 * GET /api/favorites/books
 */
export function getFavoriteBooks(params: PageParams) {
  return http.get<GetFavoriteBooksResponse>('/reading/favorites/books', params)
}

/**
 * 获取收藏绘本集列表
 * GET /api/favorites/book-sets
 */
export function getFavoriteBookSets(params: PageParams) {
  return http.get<GetFavoriteBookSetsResponse>('/reading/favorites/book-sets', params)
}

/**
 * 获取收藏音频列表
 * GET /api/favorites/audios
 */
export function getFavoriteAudios(params: PageParams) {
  return http.get<GetFavoriteAudiosResponse>('/reading/favorites/audios', params)
}

/**
 * 删除收藏项
 * DELETE /api/favorites/remove
 */
export function deleteFavorite(type: FavoriteItemType, itemId: number) {
  return httpDeleteWithBody<DeleteFavoriteResponse>('/reading/favorites/remove', {
    targetType: type,
    targetId: itemId,
  })
}

/**
 * 批量删除收藏
 * DELETE /api/favorites/batch
 */
export function batchDeleteFavorites(data: BatchDeleteFavoritesReqVO) {
  return httpDeleteWithBody<BatchDeleteFavoritesResponse>('/reading/favorites/batch', data)
}

/**
 * 添加收藏（通用接口）
 * POST /api/favorites/add
 */
export function addFavorite(type: FavoriteItemType, itemId: number) {
  return http.post<{ code: number, message: string, data: boolean }>('/reading/favorites/add', {
    targetType: type,
    targetId: itemId,
  })
}

/**
 * 检查收藏状态
 * GET /api/favorites/check
 */
export function checkFavoriteStatus(type: FavoriteItemType, itemId: number) {
  return http.get<{ code: number, message: string, data: boolean }>('/reading/favorites/check', {
    targetType: type,
    targetId: itemId,
  })
}

// ==================== 组合API函数 ====================

/**
 * 根据类型获取收藏列表
 */
export function getFavoritesByType(type: FavoriteItemType, params: PageParams) {
  switch (type) {
    case 'book':
      return getFavoriteBooks(params)
    case 'book_set':
      return getFavoriteBookSets(params)
    case 'audio':
      return getFavoriteAudios(params)
    default:
      throw new Error(`Unsupported favorite type: ${type}`)
  }
}

/**
 * 获取收藏数量
 * GET /reading/favorites/count
 */
export function getFavoriteCount(type?: FavoriteItemType) {
  return http.get<{ code: number, message: string, data: number }>('/reading/favorites/count', type ? { type } : {})
}

/**
 * 获取所有类型的收藏数量
 */
export async function getAllFavoriteCounts() {
  try {
    const [booksRes, bookSetsRes, audiosRes] = await Promise.all([
      getFavoriteCount('book'),
      getFavoriteCount('book_set'),
      getFavoriteCount('audio'),
    ])

    return {
      book: booksRes.data?.data || 0,
      book_set: bookSetsRes.data?.data || 0,
      audio: audiosRes.data?.data || 0,
    }
  }
  catch (error) {
    console.error('获取收藏数量失败:', error)
    return {
      book: 0,
      book_set: 0,
      audio: 0,
    }
  }
}

// ==================== 工具函数 ====================

/**
 * 格式化收藏时间
 */
export function formatFavoriteTime(timeStr: string, options?: {
  showTime?: boolean
  relative?: boolean
}): string {
  const { showTime = false, relative = true } = options || {}

  const date = new Date(timeStr)
  const now = new Date()
  const diffMs = now.getTime() - date.getTime()
  const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24))

  if (relative) {
    if (diffDays === 0) {
      return '今天'
    }
    else if (diffDays === 1) {
      return '昨天'
    }
    else if (diffDays < 7) {
      return `${diffDays}天前`
    }
    else if (diffDays < 30) {
      const weeks = Math.floor(diffDays / 7)
      return `${weeks}周前`
    }
    else if (diffDays < 365) {
      const months = Math.floor(diffDays / 30)
      return `${months}个月前`
    }
    else {
      const years = Math.floor(diffDays / 365)
      return `${years}年前`
    }
  }

  // 非相对时间格式
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')

  let result = `${year}-${month}-${day}`

  if (showTime) {
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    result += ` ${hours}:${minutes}`
  }

  return result
}

/**
 * 获取收藏类型的显示信息
 */
export function getFavoriteTypeInfo(type: FavoriteItemType) {
  const typeMap = {
    book: {
      label: '绘本',
      icon: 'book',
      color: '#ff6b6b',
    },
    book_set: {
      label: '绘本集',
      icon: 'folder',
      color: '#4ecdc4',
    },
    audio: {
      label: '音频',
      icon: 'sound',
      color: '#45b7d1',
    },
  }

  return typeMap[type] || typeMap.book
}

/**
 * 处理收藏项的封面URL
 */
export function processFavoriteCover(coverUrl: string): string {
  if (!coverUrl) {
    // 返回空字符串，让组件使用图标占位符
    return ''
  }

  // 如果是相对路径，添加基础URL
  if (!coverUrl.startsWith('http')) {
    const baseUrl = import.meta.env.VITE_API_BASE_URL || ''
    return `${baseUrl}${coverUrl}`
  }

  return coverUrl
}

/**
 * 生成收藏项的唯一键
 */
export function getFavoriteItemKey(item: FavoriteItem): string {
  return `${item.itemType}_${item.itemId}`
}

/**
 * 过滤收藏列表
 */
export function filterFavorites(
  items: FavoriteItem[],
  filters: {
    keyword?: string
    type?: FavoriteItemType
    dateRange?: [string, string]
  },
): FavoriteItem[] {
  let filtered = [...items]

  // 关键词过滤
  if (filters.keyword) {
    const keyword = filters.keyword.toLowerCase()
    filtered = filtered.filter(item =>
      item.title.toLowerCase().includes(keyword),
    )
  }

  // 类型过滤
  if (filters.type) {
    filtered = filtered.filter(item => item.itemType === filters.type)
  }

  // 日期范围过滤
  if (filters.dateRange) {
    const [startDate, endDate] = filters.dateRange
    filtered = filtered.filter((item) => {
      const itemDate = new Date(item.favoriteTime).getTime()
      const start = new Date(startDate).getTime()
      const end = new Date(endDate).getTime()
      return itemDate >= start && itemDate <= end
    })
  }

  return filtered
}

// ==================== 错误处理 ====================

/**
 * 处理收藏API错误
 */
export function handleFavoritesError(error: any): string {
  const errorMessages: Record<number, string> = {
    401: '请先登录',
    403: '没有权限',
    404: '收藏项不存在',
    500: '服务器错误',
    50005: '收藏项不存在',
    50001: '收藏已存在',
    50002: '收藏不存在',
    50003: '收藏类型无效',
    50004: '目标对象不存在',
  }

  // 网络错误
  if (error?.code === 'NETWORK_ERROR' || !error?.response) {
    return '网络连接失败，请检查网络后重试'
  }

  // 超时错误
  if (error?.code === 'TIMEOUT') {
    return '请求超时，请重试'
  }

  const code = error?.response?.data?.code || error?.data?.code || error?.code || error?.status
  const message = error?.response?.data?.message || error?.data?.message || error?.message

  return errorMessages[code] || message || '操作失败，请重试'
}

// ==================== 缓存相关 ====================

/**
 * 缓存键名
 */
export const CACHE_KEYS = {
  FAVORITE_BOOKS: 'favorite_books',
  FAVORITE_BOOK_SETS: 'favorite_book_sets',
  FAVORITE_AUDIOS: 'favorite_audios',
  FAVORITE_COUNTS: 'favorite_counts',
}

/**
 * 清除收藏相关缓存
 */
export function clearFavoritesCache() {
  Object.values(CACHE_KEYS).forEach((key) => {
    uni.removeStorageSync(key)
  })
}

/**
 * 缓存收藏数量
 */
export function cacheFavoriteCounts(counts: Record<FavoriteItemType, number>) {
  uni.setStorageSync(CACHE_KEYS.FAVORITE_COUNTS, counts)
}

/**
 * 获取缓存的收藏数量
 */
export function getCachedFavoriteCounts(): Record<FavoriteItemType, number> | null {
  try {
    return uni.getStorageSync(CACHE_KEYS.FAVORITE_COUNTS) || null
  }
  catch {
    return null
  }
}
